<template>
  <div>
    <!-- separator-class为图标分隔符 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="showAddForm">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名" > </el-table-column>
        <el-table-column prop="email" label="邮箱" > </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditForm(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByid(scope.row.id)"></el-button>
            <el-tooltip class="item" effect="dark" content="权限管理" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-star-off" size="mini" @click="showPowerForm(scope.row)"></el-button>
            </el-tooltip>
            </template>
             </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
  title="添加用户"
  :visible.sync="addFormDialogVisible"
  width="50%"
  @close="addFormClosed">
  <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input v-model="addForm.password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="addFormDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="修改用户"
  :visible.sync="eidtdialogVisible"
  width="50%"
  @close="eidtdialogVisibleClosed">
  <el-form :model="eidtForm" :rules="eidtFormRules" ref="eidtFormRef" label-width="100px" >
  <el-form-item label="用户名"  >
    <el-input v-model="eidtForm.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="eidtForm.email"></el-input>
  </el-form-item>
  <el-form-item label="电话" prop="mobile">
    <el-input v-model="eidtForm.mobile"></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="eidtdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUsers">确 定</el-button>
  </span>
</el-dialog>
<el-dialog
  title="分配角色"
  :visible.sync="powerDialogVisible"
  width="50%">
 <div>
   <p>当前的用户:{{userInfo.username}}</p>
   <p>当前的角色:{{userInfo.role_name}}</p>
   <p>分配新角色: <el-select v-model="setPower" placeholder="请选择" @close="setRolesClosed">
    <el-option
      v-for="item in roleslist"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select></p>
 </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="powerDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRolesPowerMsg">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
         // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userList: [],
      total: 0,
      addFormDialogVisible:false,
      addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''
      },
      addFormRules:{
          username:[
               { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ],
          password:[
               { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
          ],
          email:[
               { required: true, message: '请输入邮箱', trigger: 'blur' },
               { validator: checkEmail, trigger: 'blur' }
          ],
          mobile:[{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }]
      },
      eidtdialogVisible:false,
      eidtForm:{},
      eidtFormRules:{
          email:[
               { required: true, message: '请输入邮箱', trigger: 'blur' },
               { validator: checkEmail, trigger: 'blur' }
          ],
         mobile:[{ required: true, message: '请输入手机号', trigger: 'blur' }, { validator: checkMobile, trigger: 'blur' }]

      },
      powerDialogVisible:false,
      userInfo:{},
      roleslist:[],
      setPower:''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.userList = res.data
      //   console.log(res.data);
      //   console.log(this.userList);
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChange(row) {
      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('修改用户状态成功')
    },
    showAddForm(){
        this.addFormDialogVisible=true
    },
    addFormClosed(){
        this.$refs.addFormRef.resetFields()
    },
    addUser(){
        this.$refs.addFormRef.validate(async valid=>{
            if(!valid){
                return this.$message.error('校验失败')
            }
        const { data: res } = await this.$http.post('users', this.addForm)
           if(res.meta.status !== 201){
               return  this.$message.error('用户添加失败')
           }
           this.$message.success('添加用户成功')
           this.getUserList()
           this.addFormDialogVisible=false
        })
    },
    async showEditForm(id){
      const{data:res}= await this.$http.get('users/'+id)
      if(res.meta.status!==200){
          return this.$message.error('查询用户失败')
      }
    //   console.log(res.data);
        this.eidtForm=res.data
    
        this.eidtdialogVisible=true
    },
    eidtdialogVisibleClosed(){
         this.$refs.eidtFormRef.resetFields()
    },
    editUsers(){
         this.$refs.eidtFormRef.validate(async valid=>{
              if(!valid){
                return this.$message.error('校验失败')
            }
         const{data:res}= await  this.$http.put('users/'+this.eidtForm.id,this.eidtForm)
         if(res.meta.status!==200){
             return this.$message.error('添加失败')
         }
         this.$message.success('修改成功')
         this.getUserList()
         this.eidtdialogVisible=false
         })
    },
    async removeUserByid(id){

        const confirmResult = await this.$confirm('请问是否要永久删除该用户', '删除提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != 'confirm') {
        return this.$message.info('已经取消删除')
      }
      //发送请求根据id完成删除操作
      const { data: res } = await this.$http.delete('users/' + id)
      //判断如果删除失败，就做提示
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      //修改成功的提示
      this.$message.success('删除用户成功')
      //重新请求最新的数据
      this.getUserList()
    },
    async showPowerForm(row){
      this.userInfo=row
      const{data:res}=await this.$http.get('roles')
      if(res.meta.status!==200){
        return this.$message.error('获取角色列表失败')
      }
      this.roleslist=res.data
      this.powerDialogVisible=true
    },
    async setRolesPowerMsg(){
      if(!this.setPower){
         return this.$message.error('请输入选择的角色')
      }
      const{data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.setPower})
      if(res.meta.status!==200){
         return this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      this.getUserList()
      this.powerDialogVisible=false
    },
    setRolesClosed(){
      this.setPower=''
       this.userInfo = {}
    }
  }
}
</script>

<style lang="less" scoped>
.el-table{
    margin-top: 15px;
    margin-bottom: 15px;
}
</style>
